package thirdwork.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import thirdwork.dao.UserDao;
import thirdwork.dbutils.DBUtils;
import thirdwork.domain.Employee;
import thirdwork.domain.User;

public class UserImpl implements UserDao {
	Connection conn = DBUtils.getConnection();
	PreparedStatement ps = null;

	@Override
	public User findByName(String name) {
		User user = null;
		try {
			ps = conn.prepareStatement("select * from user where username = ?");
			ps.setString(1, name);
			ResultSet rs = ps.executeQuery();
			user = new User();
			while (rs.next()) {
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtils.closeAll();
		}
		return user;
	}

	int result;

	@Override
	public int insertUser(User user) {
		try {
			String sql = "insert into user (username,password) values (?,?)";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, user.getUsername());
			pstmt.setString(2, user.getPassword());
			result = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtils.closeAll();
		}
		return result;
	}
}
